// 配置数据
const navData = [
    {
        category: "NAS管理",
        icon: "fa-folder",
        items: [
            { 
                name: "NAS",
                icon: "fa-folder-open",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "Tr",
                icon: "fa-cloud-arrow-up",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            { 
                name: "qb",
                icon: "fa-folder-open",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "IKuai",
                icon: "fa-cloud-arrow-up",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            { 
                name: "openwrt",
                icon: "fa-folder-open",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "IYUU",
                icon: "fa-cloud-arrow-up",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            { 
                name: "xxx",
                icon: "fa-folder-open",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxx",
                icon: "fa-cloud-arrow-up",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            }
        ]
    },
    {
        category: "网址导航",
        icon: "fa-film",
        items: [
            {
                name: "影音库",
                icon: "fa-video",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxxx",
                icon: "fa-images",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "emby",
                icon: "fa-video",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "jelly",
                icon: "fa-images",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxx",
                icon: "fa-video",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxx",
                icon: "fa-images",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxx",
                icon: "fa-video",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            },
            {
                name: "xxx",
                icon: "fa-images",
                internal: "https://nas.example.com/media",
                external: "https://nas.example.com/media"
            }
        ]
    }
];

// 系统状态
let isInternalNetwork = true;
const toggleBtn = document.getElementById('toggleMode');
// 修改默认主题为黑暗模式
let currentTheme = localStorage.getItem('theme') || 'dark';

// 智能环境检测
async function detectNetwork() {
    toggleBtn.querySelector('.btn-text').textContent = '检测网络中...';
    toggleBtn.querySelector('.loading').style.display = 'inline-block';
    
    try {
        // 方法1：通过域名检测
        const isLocalIP = /(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/.test(location.hostname);
        if (isLocalIP) return true;

        // 方法2：请求检测
        const controller = new AbortController();
        setTimeout(() => controller.abort(), 1500);
        
        await fetch(navData[0].items[0].internal, {
            method: 'HEAD',
            mode: 'no-cors',
            signal: controller.signal
        });
        return true;
    } catch {
        return false;
    } finally {
        toggleBtn.querySelector('.loading').style.display = 'none';
    }
}

// 生成统计链接
function createTrackedLink(url) {
    /**
     * 访问统计实现逻辑：
     * 1. 在URL后添加from=nas_nav参数
     * 2. 区分内外网模式：nas_nav_int（内网） 和 nas_nav_ext（外网）
     * 3. 服务器可通过分析URL参数统计访问来源
     */
    const separator = url.includes('?') ? '&' : '?';
    return `${url}${separator}from=nas_nav_${isInternalNetwork ? 'int' : 'ext'}`;
}

// 渲染导航
function renderNavigation() {
    const container = document.getElementById('navContainer');
    container.innerHTML = '';

    navData.forEach(category => {
        const categoryHtml = `
            <div class="category">
                <h2><i class="fas ${category.icon}"></i> ${category.category}</h2>
                <div class="links">
                    ${category.items.map(item => `
                        <div class="link-item">
                            <a href="${createTrackedLink(isInternalNetwork ? item.internal : item.external)}"
                               target="_blank"
                               data-internal="${item.internal}"
                               data-external="${item.external}">
                                <i class="fas ${item.icon}"></i>
                                ${item.name}
                            </a>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', categoryHtml);
    });
}

// 主题切换功能
/// function toggleTheme() {
///     currentTheme = currentTheme === 'light' ? 'dark' : 'light';
///     document.documentElement.setAttribute('data-theme', currentTheme);
///     localStorage.setItem('theme', currentTheme);
///     
    // 更新按钮文字
///    const themeBtn = document.getElementById('toggleTheme');
///    themeBtn.innerHTML = currentTheme === 'light' 
///        ? '<i class="fas fa-moon"></i><span>深色模式</span>' 
///        : '<i class="fas fa-sun"></i><span>浅色模式</span>';
///}

// 搜索引擎处理
document.getElementById('searchForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const engine = document.getElementById('engineSelect').value;
    const keyword = document.getElementById('searchKeyword').value;
    
    // 构造不同搜索引擎的URL
    const engines = {
        baidu: `https://www.baidu.com/s?wd=${encodeURIComponent(keyword)}`,
        360: `https://www.so.com/s?q=${encodeURIComponent(keyword)}`
    };
    
    window.open(engines[engine], '_blank');
});

// 初始化主题
function initTheme() {
    // 从localStorage中获取主题信息
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        currentTheme = savedTheme;
    }
    document.documentElement.setAttribute('data-theme', currentTheme);
    toggleTheme(); // 强制更新按钮状态
}

// 切换网络模式
async function toggleNetwork() {
    const newMode = !isInternalNetwork;
    
    // 切换到自动模式时重新检测
    if (!localStorage.getItem('networkMode')) {
        isInternalNetwork = await detectNetwork();
    } else {
        isInternalNetwork = newMode;
    }
    
    localStorage.setItem('networkMode', isInternalNetwork ? 'internal' : 'external');
    renderNavigation();
    updateToggleButton();
}

// 更新切换按钮
function updateToggleButton() {
    toggleBtn.querySelector('.btn-text').textContent = `切换到${isInternalNetwork ? '外网' : '内网'}`;
    toggleBtn.style.backgroundColor = isInternalNetwork ? '#409EFF' : '#67C23A';
}

// 初始化
async function init() {
    // 优先读取存储，其次自动检测
    const savedMode = localStorage.getItem('networkMode');
    if (savedMode) {
        isInternalNetwork = savedMode === 'internal';
    } else {
        isInternalNetwork = await detectNetwork();
    }
    
    renderNavigation();
    updateToggleButton();
    
    // 事件监听
    document.addEventListener('click', (e) => {
        if (e.target.tagName === 'A' && !navigator.onLine) {
            alert('⚠️ 网络连接不可用，请检查网络设置');
            e.preventDefault();
        }
    });

    toggleBtn.addEventListener('click', toggleNetwork);
    
    // 初始化主题
    initTheme();
    document.getElementById('toggleTheme').addEventListener('click', toggleTheme);
}

// 启动系统
init();